#include "bookmarkmanagerxml.h"
#include "bookmarklist.h"

BookmarkManagerXml::BookmarkManagerXml()
{
    m_list = new BookmarkList();
    QFile f("bookmarklist.xml");
    m_valid = f.open(QIODevice::ReadOnly);
    if(m_valid)
    {
	QXmlStreamReader r(&f);
	m_list->deserialize(&r);
	f.close();
    }
    m_nextId = ((Resource*)m_list->at(0))->getId();
    for(int i=0;i<m_list->count();i++)
    {
	m_nextId = m_nextId < ((Resource*)m_list->at(i))->getId()?((Resource*)m_list->at(i))->getId():m_nextId;
    }
}
BookmarkManagerXml::~BookmarkManagerXml()
{
    QFile f("bookmarklist.xml");
    m_valid = f.open(QIODevice::WriteOnly);
    if(m_valid)
    {
	QXmlStreamWriter w(&f);
	m_list->serialize(&w);
	f.close();
    }
    delete m_list;
}
ResourceList* BookmarkManagerXml::getResources()
{
   return m_list;
}
bool BookmarkManagerXml::addResource(Resource *r)
{
    r->setId(getNextId());
    m_list->append(r);
    return true;
}
bool BookmarkManagerXml::updateResource(Resource * r)
{
    int count = m_list->count();
    for(int i=0;i<count;i++)
    {
	Bookmark* b = (Bookmark*)m_list->at(i);
	if(b->getId() == r->getId())
	{
	    b->setChapitre(((Bookmark*)r)->chapitre());
	    b->setPage(((Bookmark*)r)->page());
	    b->setFinAtteinte(((Bookmark*)r)->finAtteinte());
	    b->setManga(((Bookmark*)r)->manga());
	}
    }
    return true;
}
bool BookmarkManagerXml::deleteResource(Resource * r)
{
    int count = m_list->count();
    for(int i=0;i<count;i++)
    {
	Bookmark* b = (Bookmark*)m_list->at(i);
	if(b->getId() == r->getId())
	{
	    m_list->removeAt(i);
	}
    }
    return true;
}
QString BookmarkManagerXml::getLastError()
{
    return "";
}
